package com.jt.config;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.pool.PoolStats;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * 定期将超时的连接关闭
 * @author dc
 */
@Component
public class HttpClientClose extends Thread{

	@Autowired
	private PoolingHttpClientConnectionManager manage;

	/**开关 volatile表示多线程可变数据,一个线程修改,其他线程立即修改(可见性)*/
	private volatile boolean shutdown;
	
	public HttpClientClose() {
		//线程开启启动
		this.start();
	}
	
	
	@Override
	public void run() {
		try {
			//如果服务没有关闭,执行线程
			while(!shutdown) {
				synchronized (this) {
					//等待5秒
					wait(5000);
					/**方便打桩时观察连接状态*/
					PoolStats stats = manage.getTotalStats();
					//获取可用的线程数量
					int av = stats.getAvailable();
					//获取阻塞的线程数量
					int pend = stats.getPending();
					//获取当前正在使用的链接数量
					int lea = stats.getLeased();
					int max = stats.getMax();
					//关闭超时的链接
					manage.closeExpiredConnections();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}

		super.run();
	}

	/**
	 * 关闭清理无效连接的线程
	 * 容器关闭时执行该方法.
	 */
	@PreDestroy
	public void shutdown() {
		shutdown = true;
		synchronized (this) {
			//将run方法全部从等待中唤醒.执行关闭操作;
			notifyAll();
		}
	}
}
